package com.cqut.utils;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class DBUtils {
    //增加、修改、删除SQL
    public static int Update(String sql,Object... params) {
        Connection connection = null;
        try{
            connection = DruidUtils.getConnection();
            QueryRunner queryRunner = new QueryRunner();
            int update = queryRunner.update(connection,sql,params);
            return update;
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            DruidUtils.close(null,null,connection);
        }
    }
    //获取一个值 count（*）
    public static Object QueryScalar(String sql,Object... params) {
        Connection connection = null;
        try{
            connection = DruidUtils.getConnection();
            QueryRunner queryRunner = new QueryRunner();
            Object obj = queryRunner.query(connection,sql,new ScalarHandler(),params);
            return obj;
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            DruidUtils.close(null,null,connection);
        }
    }
    //获取一条数据
    public static <T> T QueryBean(String sql,Class<T> clazz,Object... params) throws SQLException {
        Connection connection = DruidUtils.getConnection();
        QueryRunner queryRunner = new QueryRunner();
        T query = queryRunner.query(connection,sql,new BeanHandler<T>(clazz),params);
        return query;
    }

    //获取多条数据
    public static <T> List<T> QueryBeanList(String sql,Class<T> clazz,Object... params) throws SQLException {
        Connection connection = null;
        try{
            connection = DruidUtils.getConnection();
            QueryRunner queryRunner = new QueryRunner();
            List<T> list = queryRunner.query(connection,sql,new BeanListHandler<T>(clazz),params);
            return list;
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            DruidUtils.close(null,null,connection);
        }
    }

}
